package cn.wolfcode.cms.service.impl;

import cn.wolfcode.cms.domain.Collect;
import cn.wolfcode.cms.domain.Member;
import cn.wolfcode.cms.domain.MemberSpend;
import cn.wolfcode.cms.mapper.CollectMapper;
import cn.wolfcode.cms.mapper.MemberMapper;
import cn.wolfcode.cms.mapper.MemberSpendMapper;
import cn.wolfcode.cms.query.QueryObject;
import cn.wolfcode.cms.service.ICollectService;
import cn.wolfcode.cms.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CollectServiceImpl implements ICollectService {

    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MemberSpendMapper memberSpendMapper;

    public void save(Collect entity) {
        collectMapper.insert(entity);

    }

    public void update(Collect entity) {
        collectMapper.updateByPrimaryKey(entity);
    }

    public void delete(Long id) {
        collectMapper.deleteByPrimaryKey(id);
    }

    public Collect get(Long id) {
        return collectMapper.selectByPrimaryKey(id);
    }

    public List<Collect> list() {
        return collectMapper.selectAll();
    }

    public Object query(QueryObject qo) {
        //查总数
        int total = collectMapper.queryForCount(qo);
        if (total == 0) {
            return new PageResult();
        }
        //查数据
        List<Collect> rows = collectMapper.queryForList(qo);
        return new PageResult(total, rows);
    }

    public void updateCollect(Map<String, String> map) {
        String sid = map.get("id");
        String realpay = map.get("allM");
        MemberSpend memberSpend = memberSpendMapper.selectByMemberId(Long.valueOf(sid));
        //==================总消费表增加花费余额
        if (memberSpend == null) {
            memberSpend = new MemberSpend();
            memberSpend.setTotalspend(Long.valueOf(realpay));
        } else {
            memberSpend.setTotalspend(memberSpend.getTotalspend() + Long.valueOf(realpay));
            memberSpendMapper.updateSpendById(memberSpend);
        }
        //==================会员减少余额
        Member member = memberMapper.getCardNumById(Long.valueOf(sid));
        if (member.getBalance().compareTo(new BigDecimal(realpay)) < 0) {
            member.setBalance(new BigDecimal("0"));
        } else {
            member.setBalance(member.getBalance().subtract(new BigDecimal(realpay)));
        }
        member.setIntegral(member.getIntegral() + Integer.valueOf(realpay));
        memberMapper.updateBalanceById(member);
        //==================
        Collect collect = new Collect();
        collect.setSpendtime(new Date());
        collect.setRealpay(Long.valueOf(realpay));
        collect.setCard_num(member.getCardNum());
        collectMapper.insert(collect);
    }

}
